package com.hbwxz.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * RabbitMQ 工具类
 *
 * @author shenzw
 * @date 2023/11/11
 */
public class RabbitMqUtils {

    private RabbitMqUtils() {
    }

    /**
     * 获取信道 Channel
     *
     * @return Channel
     */
    public static Channel getChannel() throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        // 不能用 tru-with-resource，不然会提前关闭 RabbitMQ 连接，导致没有正确路由到 Queue 队列也不会产生回调操作
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        return channel;
    }

    /**
     * 创建 exchange，queue，绑定关系
     *
     * @param exchange     交换机名称
     * @param exchangeType 交换机类型【fanout；direct；topic；headers】
     * @param queue        队列名称
     * @param routingKey   路由 Key
     */
    public static void installRabbitMq(String exchange, String exchangeType, String queue, String routingKey) throws IOException, TimeoutException {
        Channel channel = getChannel();
        channel.exchangeDeclare(exchange, exchangeType, true); // 交换机的名字，交换机的类型，是否持久化
        channel.queueDeclare(queue, true, false, false, null);
        channel.queueBind(queue, exchange, routingKey); // 队列，交换机，routingKey
    }

    /**
     * 关闭连接
     *
     * @param channel 信道
     */
    public static void close(Channel channel) throws IOException, TimeoutException {
        channel.close();
        channel.getConnection().close();
    }
}
